<?php
	function logoutUser() {
		$uid;
		$time_out=120;
		$user;
		$valid=false;
		$remote_ip = $_SERVER['REMOTE_ADDR'];
		
		$con = mysql_connect('localhost','root','') or die(mysql_error());
		mysql_SELECT_db("sistema", $con) or die(mysql_error());
		
		$res = mysql_query("SELECT user_id, session_id, status, (now()-last_access)/60 as duration FROM session_log WHERE remote_ip='$remote_ip' AND session_id=(SELECT max(session_id) FROM session_log WHERE remote_ip='$remote_ip');", $con)  or die(mysql_error());
		$session_id = mysql_result($res,0,"session_id");
		if(mysql_num_rows($res) == 0 || mysql_result($res,0,"status") == "EXPIRED") {
			/*print("<center><h1>Invalid Session!</h1><br />");
			mysql_close($con);
			print("<a href='index.php'>Go to Login Page</a></center>");
			exit(0);*/
			header("Location: index.php");
		}
		else if(mysql_result($res,0,"duration") > $time_out) {
			/*print("<center><h1>Session timed out!</h1></center><br />");
			$res = mysql_query("SELECT @m:=max(session_id) FROM session_log WHERE remote_ip='$remote_ip';", $con);
			$res = mysql_query("update session_log set status=2 WHERE remote_ip='$remote_ip' AND session_id=@m;", $con)  or die(mysql_error());
			mysql_close($con);
			print("<a href='index.php'>Go to Login Page</a>");
			exit(0);*/
			header("Location: index.php");
		}

		$uid = mysql_result($res,0,"user_id");
		$res = mysql_query("SELECT nome_completo FROM usuarios WHERE idusuarios=$uid;", $con)  or die(mysql_error());
		$user = mysql_result($res,0,"nome_completo");
		$res = mysql_query("update session_log set status=2, last_access=now() WHERE remote_ip='$remote_ip' AND session_id=$session_id;", $con)  or die(mysql_error());
		//print("<center><h1>Successfully logged out $user!</h1><br />");
		//print("<a href='index.html'>Return to login page</a></center>");

		$res = mysql_query("update session_log set status=2 WHERE (now()-last_access)/60 >= $time_out;", $con)  or die(mysql_error());
		
		mysql_close($con);
		
	}
	logoutUser();
	header("Location: index.php");
?>